<?php
namespace  Ekadmin\Controller;
use \Think\Controller;
use Think\Page;
use App\Config\YlyConfig;
use App\Oauth\YlyOauthClient;
use App\Api\PrintService;
use App\Api\PicturePrintService;
use App\Api\ExpressPrintService;

class StorageController extends CommonController{
    
    //首页显示内容
    /*@根据当天活动显示当前商品销售额*/
    public function index(){
        
        $activity=I("activity");
        
        $this->activity=$activity;
        


        $rs=M("activity")->where("uniacid=".$this->uniacid)->select();
        $this->activity=$rs;

        if($activity){
            $where="id=".$activity." and uniacid=".$this->uniacid;
            $rs=M("activity")->where($where)->find();
        }else{
            $rs=M("activity")->where("uniacid=".$this->uniacid)->order("id desc")->find();
        }
        
        $activity=$rs["id"];
        
        if($rs){
            $activityname=$rs["name"];    
            $tmp_xiaoqu=array();
            $goods=explode(",", $rs["goods_ids"]);//获取所有活动商品Id
            $tmp_goods=array();
            foreach ( $goods as $v){
                $tmp_goods[$v]=0;
            }
            $goods=$tmp_goods;//商品Id数组 
            
            if($rs["is_limit_xiaoqu"]==2){
                //指定小区时，用于覆盖线路小区
                $xiaoqu=explode(",",$rs["allow_xiaoqu_ids"]);
                foreach($xiaoqu as $v){
                    $tmp_xiaoqu[$v]=array("num"=>0,"goodsid"=>$goods);
                }
                $xiaoqu=$tmp_xiaoqu;

            }else{
                
                $xiaoqu=M("xiaoqu")->field("id")->where("status=1 and uniacid=".$this->uniacid)->order("id desc")->select();
                foreach($xiaoqu as $v){
                    $tmp_xiaoqu[$v["id"]]=array("num"=>0,"goodsid"=>$goods);
                }
                $xiaoqu=$tmp_xiaoqu;

            }
            
            //线路
            $quyu=M("quyu")->where("uniacid=".$this->uniacid)->order(" id desc")->select();
            
            $tmp_quyu=array();
            foreach ( $quyu as $v){
                $tmp_quyu[$v["id"]]=array("num"=>0,"xiaoqu"=>array(),"goodsid"=>$goods);
            }
            $quyu=$tmp_quyu;
            
            //总团长
            $zongtuanzhang=M("zongtuanzhang")->where("uniacid=".$this->uniacid)->order(" id desc")->select();
            $tmp_zongtuanzhang=array();
            
            foreach ( $zongtuanzhang as $v){
                //如果总团长里没有小区，则将总团长当团长对待，总团长名单不会在总团长里显示
                if(trim($v["uuid"])!=""){
                    $a_arr=explode(",",$v["uuid"]);
                    $tmp_zongtuanzhang[$v["uid"]]=array("num"=>0,"xiaoqu"=>$a_arr,"goodsid"=>$goods);
                }
            }
            $zongtuanzhang=$tmp_zongtuanzhang;
            
            $where2=" activity_id=".$activity." and is_pay=2 and uniacid=".$this->uniacid;// 
            
            $result=M("order")->where($where2)->order("id desc")->select();
            
            
            if(!$result){
                $this->display();
                exit;
            }

            foreach ($result as $v){

                $rt=M("refund")->where("out_trade_no='".$v["out_trade_no"]."' and status=2 and uniacid=".$this->uniacid)->find();
                if(!$rt){
                    $goodsinfo=json_decode($v["goodsinfo"],true);
                
                    foreach($goodsinfo as $s){
                
                
                        $goods[$s["id"]]+=$s["num"];//商品
                        $xiaoqu[$v["xiaoqu_id"]]["num"]+=$s["num"];//小区商品总数量
                        $xiaoqu[$v["xiaoqu_id"]]["goodsid"][$s["id"]]+=$s["num"];//小区商品分类数量
                        foreach($zongtuanzhang as $vvk=>$vva){
                            if(in_array($v["xiaoqu_id"],$vva["xiaoqu"])){
                                $zongtuanzhang[$vvk]["num"]+=$s["num"];
                                $zongtuanzhang[$vvk]["goodsid"][$s["id"]]+=$s["num"];
                            }
                        }               
                        $quyu[$v["quyu_id"]]["num"]+=$s["num"];//线路商品总数数量
                        $quyu[$v["quyu_id"]]["goodsid"][$s["id"]]+=$s["num"];//线路商品分类数量
                
                
                    }
                }
                
            }

            
            $tmp_goods=array();//商品信息
            foreach($goods as $k=>$v){
                if($v>0){
                    $rs=M("goods")->field("name")->find($k);
                    $d=array("name"=>$rs["name"],"num"=>$v);
                    $tmp_goods[$k]=$d;
                }else{
                    unset($goods[$k]);
                }
            }
            
            $this->goods=$tmp_goods;
            
            
            foreach($quyu as $k=>$v){
                foreach ($v["goodsid"] as $kk =>$vv){
                    if($vv==0){
                        unset($quyu[$k]["goodsid"][$kk]);
                    }else{
                        $d=array("name"=>$tmp_goods[$kk]["name"],"num"=>$vv);
                        $quyu[$k]["goodsid"][$kk]=$d;
                    }
                }
            }
            
            foreach($zongtuanzhang as $k=>$v){
                if($v["num"]==0){
                    unset($zongtuanzhang[$k]);
                }else{
                    $rt=M("xiaoqu")->where("uid=".$k)->find();
                    $zongtuanzhang[$k]["info"]="总团长姓名：".$rt["tuan_name"]."  手机号：".$rt["mobile"];
            
                    foreach ($v["goodsid"] as $kk =>$vv){
                        if($vv==0){
                            unset($zongtuanzhang[$k]["goodsid"][$kk]);
                        }else{
                            $d=array("name"=>$tmp_goods[$kk]["name"],"num"=>$vv);
                            $zongtuanzhang[$k]["goodsid"][$kk]=$d;
                        }
                    }
                }
            }
            
            
            foreach($xiaoqu as $k=>$v){
                if($v["num"]>0){
                    $rs=M("xiaoqu")->find($k);
                    $xiaoqu[$k]["xiaoqu_name"]=$rs["name"];
                    $xiaoqu[$k]["tuan_name"]=$rs["tuan_name"];
                    $xiaoqu[$k]["mobile"]=$rs["mobile"];
                    $xiaoqu[$k]["address"]=$rs["address"];
                    foreach($zongtuanzhang as $akk=>$avv){
                        if(in_array($k,$avv["xiaoqu"])){
                            $xiaoqu[$k]["flag"]=$zongtuanzhang[$akk]["info"];
                        }else{
                            $xiaoqu[$k]["flag"]="";
                        }
                    }
                    
                    foreach ($v["goodsid"] as $kk=>$vv){
                        if($vv>0){
                            $xiaoqu[$k]["goodsid"][$kk]=array("name"=>$tmp_goods[$kk]["name"],"num"=>$vv);
                        }else{
                            unset($xiaoqu[$k]["goodsid"][$kk]);
                        }
                    }
                    array_push($quyu[$rs["quyu_id"]]["xiaoqu"], $xiaoqu[$k]);
                }else{
                    unset($xiaoqu[$k]);
                }
            }
            
            foreach($quyu as $k=>$v){
                $rs=M("quyu")->find($k);
                $quyu[$k]["name"]=$rs["name"];
            }
            $this->tuanzhang=$zongtuanzhang;
            
            $this->quyu=$quyu;
            //$this->printx("相关信息：", $quyu);
            $this->display();
            
        }else{
            $this->goods=array();
            $this->tuanzhang=array();
            $this->quyu=array();
            $this->display();
       }     

    }
 
    
    public function exportprint(){
       /*查询代码开始*/ 
        $activity=I("activity");
        
        $rs=M("activity")->where("uniacid=".$this->uniacid)->select();
        
        if($activity){
            $where="id=".$activity." and uniacid=".$this->uniacid;
            $rs=M("activity")->where($where)->find();
        }else{
            $rs=M("activity")->where("uniacid=".$this->uniacid)->order("id desc")->find();
        }
        
        $activity=$rs["id"];
        
        if($rs){
                $activityname=$rs["name"];
                $tmp_xiaoqu=array();
                $goods=explode(",", $rs["goods_ids"]);//获取所有活动商品Id
                $tmp_goods=array();
                foreach ( $goods as $v){
                    $tmp_goods[$v]=0;
                }
                $goods=$tmp_goods;//商品Id数组
            
                if($rs["is_limit_xiaoqu"]==2){
                    //指定小区时，用于覆盖线路小区
                    $xiaoqu=explode(",",$rs["allow_xiaoqu_ids"]);
                    foreach($xiaoqu as $v){
                        $tmp_xiaoqu[$v]=array("num"=>0,"goodsid"=>$goods);
                    }
                    $xiaoqu=$tmp_xiaoqu;
            
                }else{
            
                    $xiaoqu=M("xiaoqu")->field("id")->where("status=1  and uniacid=".$this->uniacid)->order("id desc")->select();
                    foreach($xiaoqu as $v){
                        $tmp_xiaoqu[$v["id"]]=array("num"=>0,"goodsid"=>$goods);
                    }
                    $xiaoqu=$tmp_xiaoqu;
            
                }
        
            //线路
                $quyu=M("quyu")->where("uniacid=".$this->uniacid)->order(" id desc")->select();
            
                $tmp_quyu=array();
                foreach ( $quyu as $v){
                    $tmp_quyu[$v["id"]]=array("num"=>0,"xiaoqu"=>array(),"goodsid"=>$goods);
                }
                $quyu=$tmp_quyu;
            
                //总团长
                $zongtuanzhang=M("zongtuanzhang")->where("uniacid=".$this->uniacid)->order(" id desc")->select();
                $tmp_zongtuanzhang=array();
                
                foreach ( $zongtuanzhang as $v){
                    //如果总团长里没有小区，则将总团长当团长对待，总团长名单不会在总团长里显示
                    if(trim($v["uuid"])!=""){
                        $a_arr=explode(",",$v["uuid"]);
                        $tmp_zongtuanzhang[$v["uid"]]=array("num"=>0,"xiaoqu"=>$a_arr,"goodsid"=>$goods);
                    }
                }
                $zongtuanzhang=$tmp_zongtuanzhang;
                
                
                $where2=" activity_id=".$activity." and is_pay=2 and uniacid=".$this->uniacid;//
            
                $result=M("order")->where($where2)->order("id desc")->select();
            
            
                if(!$result){
                    exit;
                }
        
                foreach ($result as $v){
            
                    $rt=M("refund")->where("out_trade_no='".$v["out_trade_no"]."' and status=2 and uniacid=".$this->uniacid)->find();
                    if(!$rt){
                        $goodsinfo=json_decode($v["goodsinfo"],true);
                        foreach($goodsinfo as $s){
                            $goods[$s["id"]]+=$s["num"];//商品
                            $xiaoqu[$v["xiaoqu_id"]]["num"]+=$s["num"];//小区商品总数量
                            $xiaoqu[$v["xiaoqu_id"]]["goodsid"][$s["id"]]+=$s["num"];//小区商品分类数量
                            
                            foreach($zongtuanzhang as $vvk=>$vva){
                                if(in_array($v["xiaoqu_id"],$vva["xiaoqu"])){
                                    $zongtuanzhang[$vvk]["num"]+=$s["num"];
                                    $zongtuanzhang[$vvk]["goodsid"][$s["id"]]+=$s["num"];
                                }
                            }
                            
                            $quyu[$v["quyu_id"]]["num"]+=$s["num"];//线路商品总数数量
                            $quyu[$v["quyu_id"]]["goodsid"][$s["id"]]+=$s["num"];//线路商品分类数量
                        }
                    }           
                }
            
            
                $tmp_goods=array();//商品信息
                foreach($goods as $k=>$v){
                    if($v>0){
                        $rs=M("goods")->field("name")->find($k);
                        $d=array("name"=>$rs["name"],"num"=>$v);
                        $tmp_goods[$k]=$d;
                    }else{
                        unset($goods[$k]);
                    }
                }
            
                $goods=$tmp_goods;
            
            
                foreach($quyu as $k=>$v){
                    foreach ($v["goodsid"] as $kk =>$vv){
                        if($vv==0){
                            unset($quyu[$k]["goodsid"][$kk]);
                        }else{
                            $d=array("name"=>$tmp_goods[$kk]["name"],"num"=>$vv);
                            $quyu[$k]["goodsid"][$kk]=$d;
                        }
                    }
                }
            
                foreach($zongtuanzhang as $k=>$v){
                    if($v["num"]==0){
                        unset($zongtuanzhang[$k]);
                    }else{
                        $rt=M("xiaoqu")->where("uid=".$k)->find();
                        $zongtuanzhang[$k]["info"]="姓名：".$rt["tuan_name"]."  手机号：".$rt["mobile"];
                
                        foreach ($v["goodsid"] as $kk =>$vv){
                            if($vv==0){
                                unset($zongtuanzhang[$k]["goodsid"][$kk]);
                            }else{
                                $d=array("name"=>$tmp_goods[$kk]["name"],"num"=>$vv);
                                $zongtuanzhang[$k]["goodsid"][$kk]=$d;
                            }
                        }
                    }
                }
                
                foreach($xiaoqu as $k=>$v){
                    if($v["num"]>0){
                        $rs=M("xiaoqu")->find($k);
                        $xiaoqu[$k]["xiaoqu_name"]=$rs["name"];
                        $xiaoqu[$k]["tuan_name"]=$rs["tuan_name"];
                        $xiaoqu[$k]["mobile"]=$rs["mobile"];
                        $xiaoqu[$k]["address"]=$rs["address"];
                        foreach($zongtuanzhang as $akk=>$avv){
                            if(in_array($k,$avv["xiaoqu"])){
                                $xiaoqu[$k]["flag"]=$zongtuanzhang[$akk]["info"];
                            }else{
                                $xiaoqu[$k]["flag"]="";
                            }
                        }           
            
                        foreach ($v["goodsid"] as $kk=>$vv){
                            if($vv>0){
                                $xiaoqu[$k]["goodsid"][$kk]=array("name"=>$tmp_goods[$kk]["name"],"num"=>$vv);
                            }else{
                                unset($xiaoqu[$k]["goodsid"][$kk]);
                            }
                        }
                        array_push($quyu[$rs["quyu_id"]]["xiaoqu"], $xiaoqu[$k]);
                    }else{
                        unset($xiaoqu[$k]);
                    }
                }
            
                foreach($quyu as $k=>$v){
                    $rs=M("quyu")->find($k);
                    $quyu[$k]["name"]=$rs["name"];
                }        
        /*查询代结束*/
    
                Vendor('lib.Autoloader');
            
                Vendor('lib.Config.YlyConfig');
            
                $map['uniacid'] = $this->uniacid;
            
                $data  = M('config')->where($map)->find();
                 
                if(empty($data['clientid']) || empty($data['clientsecret']) || empty($data['granttype']) || empty($data['ptr_code']) ){
                    exit("系统打印机设置没有配置");
                }
            
                $grantType = $data['granttype'];                     //'client_credentials' 自有型应用;
            
                define('GRANTTYPE', $grantType);
            
                $clientId = $data["clientid"];                       //应用id
            
                $clientSecret = $data["clientsecret"];;              //应用密钥
            
                $config=new YlyConfig($clientId, $clientSecret);
        
        
                if (GRANTTYPE == 'client_credentials') {            //'client_credentials' 自有型应用;
            
                        $refresh_token =  S('refreshConfig');
                        $access_token = S('accessConfig');
                
                        if(!$refresh_token)
                        {
                            $client = new YlyOauthClient($config);
                            try {
                                $token = $client->getToken();
                            } catch (Exception $e) {
                                echo $e->getMessage() . "\n";
                                print_r(json_decode($e->getMessage(), true));
                                return;
                            }
                
                            $access_token = $token->access_token;           //调用API凭证AccessToken 永久有效,请妥善保存.
                            $refresh_token = $token->refresh_token;         //刷新AccessToken凭证 失效时间35天
                            $expires_in = $token->expires_in;               //自有型应用可忽略此回调参数, AccessToken失效时间30天
                
                            S('refreshConfig',$refresh_token,259000);
                            S('accessConfig',$access_token,259000);
                        }
                        /*获取订单信息开始*/
                
                        $machine_code = $data['ptr_code'];          //机器码4004585701
                
                        $origin_id = '打印时间：'.date("YmdHis");                    //内部订单号(32位以内)
                        /*获取订单信息结束*/
                        if (empty($machine_code)) {echo 'The machine_code cannot be empty';return;}
                
                        if (empty($origin_id)) {echo 'The origin_id cannot be empty';return;}
                
                        /**文本接口开始**/
                        $print = new PrintService($access_token, $config);
                        //58mm排版 排版指令详情请看 http://doc2.10ss.net/332006
                        $content = "<FS2><center>**#1".$data['ptr_platform']."打印**</center></FS2>";
                        $content .= str_repeat('.', 32);
                        $content .= "<FS2><center>--仓储配货--</center></FS2>";
                        $content .= "<FS><center>".$data['ptr_xcxname']."</center></FS>";
                        //
                        $content .= "<FH><center>".$activityname."</center></FH>";
                        $content .= "<FH><center>商品总数量</center></FH>";
                        foreach($goods as $v){
                            $content .= $v["name"].":".$v["num"]."\n";
                        }
                        $content .= str_repeat('+', 32)."\n";
                        try{
                        
                            $print->index($machine_code, $content, $origin_id);
                        
                        }catch (Exception $e) {
                            echo $e->getMessage();
                        }
                        if(count($zongtuanzhang)){
                             $content = "<FH><center>总团长明细</center></FH>";
                             foreach($zongtuanzhang as $v){
                                 $content .= "总团长:".$v["info"]."\n";
                                 $content .= "商品总数:".$v["num"]."\n";
                                 foreach($v["goodsid"] as $vv){
                                 $content .= "商品名称:".$vv["name"]."\n";
                                 $content .= "商品总数:".$vv["num"]."\n";
                             }
                             $content .= str_repeat('+', 32)."\n";
                        
                             try{
                            
                             $print->index($machine_code, $content, $origin_id);
                            
                             }catch (Exception $e) {
                                 echo $e->getMessage();
                             }
                        }
                    }
                    
                    
                    $content = "<FH><center>配货明细</center></FH>";
                    foreach($quyu as $k=>$v){
                        $content .= "线路:".$v["name"]."\n";
                        $content .= "商品总数量:".$v["num"]."\n";
                        $content .= "线路小区数量:".count($v["xiaoqu"])."\n";
                        foreach ($v["goodsid"] as $y){
                            $content .= "商品名称:".$y["name"]."\n";
                            $content .= "商品总数量:".$y["num"]."\n";
                        }
                        //$content .= str_repeat('=', 32)."\n";
                        foreach($v['xiaoqu'] as $kk=>$vv){
                            $content .= "名称:".$vv["xiaoqu_name"]."\n";
                            $content .= "姓名:".$vv["tuan_name"]."\n";
                            $content .= "手机号:".$vv["mobile"]."\n";
                            $content .= "地址:".$vv["address"]."\n";
                            $content .= "总数量:".$vv["num"]."\n";
                            if($vv["flag"]!=""){
                                $content .= "总团长: ".$vv["num"]."\n";
                            }
                            //$content .= str_repeat('-', 32)."\n";
                            foreach($vv["goodsid"] as $aa =>$bb){
                                $content .= "商品名称:".$bb["name"]."\n";
                                $content .= "商品数量:".$bb["num"]."\n";
                            }
                    
                        }
                        try{
                    
                            $print->index($machine_code, $content, $origin_id);
                    
                        }catch (Exception $e) {
                            echo $e->getMessage();
                        }
                        $content="";
                    }
                    
                    //                     $content .= str_repeat('*', 32);
                    //                     $content .= "<FS2><center>**#1 完**</center></FS2>";
                    //                     try{
                    //                         $print->index($machine_code, $content, $origin_id);
                    //                         $this->success("打印成功");
                    //                     }catch (Exception $e) {
                    //                         echo $e->getMessage();
                    //                     }
                    $this->success("打印成功");
                    /**文本接口结束**/
                    
                }
            
                if (GRANTTYPE == 'authorization_code') {
                    include_once __DIR__ . '/AuthorizationCodeMode/callback.php';//开放型应用
                }
        }
    } 
    
    
    /**
     *@仓储订单打印-订单导出 
     * @param unknown $name
     * @param unknown $arr
     */
    public function orderprint(){
        $where ="uniacid =". $this->uniacid;
        
        $activity=I("activity");
        
        $this->activity=$activity;
        
        
        
        $rs=M("activity")->where("uniacid=".$this->uniacid)->select();
        $this->activity=$rs;
        
        if($activity){
            $where="id=".$activity." and uniacid=".$this->uniacid;
            $rs=M("activity")->where($where)->find();
        }else{
            $rs=M("activity")->where("uniacid=".$this->uniacid)->order("id desc")->find();
        }
        
        $activity=$rs["id"];
        $activename=$rs["name"];
        
        $xlsCell = array(
            [
                'quyu',
                '线路'
            ],
        
            [
                'xiaoqu',
                '小区名称'
            ],
        
            [
                'active',
                '活动名称'
            ],
        
            [
                'tuan_name',
                '团长姓名'
            ],
            [
                'out_trade_no',
                '订单编号'
            ],
            [
                'uid',
                '会员信息'
            ],
        
            [
                'total_jiner',
                '订单总金额'
            ],
            [
                'goods',
                '订单商品'
            ],
            [
                'addtime',
                '下单时间'
            ],
            [
                'name',
                '收货人'
            ],
            [
                'mobile',
                '联系方式'
            ],
            [
                'address',
                '地址'
            ],
            [
                'is_pay',
                '支付状态'
            ],
            [
                'is_send',
                '发货状态'
            ],
            [
                'peisong_type',
                '配送类型'
            ]
        ); // ->field('out_trade_no,uid,total_jiner,addtime,name,mobile,address,goods_id,is_pay,is_send,goodsinfo')
        
        $where2=" uniacid=".$this->uniacid." and activity_id=".$activity." and is_pay=2 and tui_status=1";//
        
        $data=M("order")->where($where2)->order("id desc")->select();
        
        $goodsobj = M('goods');
        foreach ($data as $k => $v) {
            $rs = M("quyu")->where("id=".$v["quyu_id"]." and uniacid=".$this->uniacid)->find();
        
            $data[$k]['quyu'] = $rs["name"];
        
            $rs = M("xiaoqu")->where(" id=".$v["xiaoqu_id"]." and uniacid=".$this->uniacid)->find();
        
            $data[$k]["xiaoqu"] = $rs["name"];
        
            $data[$k]["tuan_name"] = $rs["tuan_name"];
        
            $rs = M("activity")->where("id=".$v["activity_id"]." and uniacid=".$this->uniacid)->find();
        
            $data[$k]["active"] = $rs["name"];
        
            $data[$k]['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
            $data[$k]['out_trade_no'] = "\t" . $v['out_trade_no'] . "\t";
            $data[$k]['address'] = $v['address'];
            $data[$k]['uid'] = $v['name']; // .' | 会员ID:'.$v['uid']
            $data[$k]['is_pay'] = $v['is_pay'] == 1 ? '未支付' : '已支付';
            $data[$k]['is_send'] = $v['is_send'] == 1 ? '未发货' : '已发货';
            switch($data[$k]['peisong_type']){
                case 1:
                    $data[$k]['peisong_type']="自提";
                    break;
                case 2:
                    $data[$k]['peisong_type']="送货上门";
                    break;
                default:
                    $data[$k]['peisong_type']="自定义";
                    break;
            }
        
            $goodsinfo = json_decode($v['goodsinfo'], true);
        
            $str = "";
            foreach ($goodsinfo as $kk => $vs) {
        
                $rets = $goodsobj->where("id=".$vs["id"]." and uniacid=".$this->uniacid)->find();
                if ($str == "") {
                    $str .= $rets["name"] . "*" . $vs["num"];
                } else {
                    $str .= ',' . $rets["name"]. "*" . $vs["num"];
                    // $str.=',商品Id：'.$vs["id"].' 商品名称：'.$rets["name"].","."团购价格".$vs["tuan_price"]." 购买数量".$vs["num"];
                }
            }
            $data[$k]['goods'] = $str;
        }
        
        if ($data) {
            $title = date("YmdHis") . "订单";
            exportExcel($title, $xlsCell, $data);
        } else {
        
            $this->error("没有记录");
            //echo "<script>alert('没有记录');</script>";
            //exit();
        }
    }
    
    public function printx($name,$arr){
        echo $name;
        echo "<pre>";
        print_r($arr);
        echo "</pre>";
    }

}

?>